<?php
// +----------------------------------------------------------------------
// | Created by Sublime: [ Conqweal ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021~20223[chenjia] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.99dn.cn
// +----------------------------------------------------------------------
// | Author: Conqweal <150672834@qq.com>
// +----------------------------------------------------------------------
// | Date: 2021/12/22 0026
// +----------------------------------------------------------------------
// | Description:信息接口
// +----------------------------------------------------------------------
namespace app\api\controller;

use app\Api;
use app\api\model\Info as cModel;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Validate;
use app\ApiController;
use support\Request;
use support\Util\InitTree;

class InfoController extends ApiController
{
    protected $noNeedLogin = ['index', 'getOptions', 'contributeList', 'detail', 'listbycat'];
    protected $noNeedRight = '*';

    public function _initialize()
    {

        parent::_initialize();

    }

    /**
     * 任务大厅
     * @return \think\response\Json
     * @throws \\Exception
     */
    public function index()
    {

        $limit = $this->request->get('limit', 10);
        $w     = [];

        if ($this->request->get('title')) {
            $w[] = ['b.title', 'like', '%' . $this->request->get('title') . '%'];

        }
        if ($this->request->get('brief')) {
            $w[] = ['b.brief', 'like', '%' . $this->request->get('brief') . '%'];

        }
        if ($this->request->get('seo')) {
            $w[] = ['b.seo->meta_title|b.seo->meta_keyword|b.seo->meta_description', 'like', '%' . $this->request->get('seo') . '%'];

        }

        $q = cmodel::alias('a')->join("info_description b", "a.info_id=b.info_id and b.language_id=" . $this->lang_id, 'left')->field("a.*,b.title,b.content,b.brief,b.seo")->where($w);

        if ($this->request->get('cat_id')) {
            $q->join("info_cat c", "c.info_id=a.info_id")->where('c.cat_id', $this->request->get("cat_id"));
        }

        $ls = $q->paginate(['list_rows' => $limit, 'request' => $this->request->all()]);

        $res = $ls->items();

        $res = array_map(function ($v) {

            $v->cat_name = $this->getLangCatName($v);
            $v->route = createUrl('art',$v->title,$v->info_id);
            return $v;
        }, $res);

        $data['ls']    = $res;
        $data['total'] = $ls->total();
        return $this->success(__('Operation successful'), $data);

    }

    /**
     * 获取选项或者辅助参数
     * @return [type] [description]
     */
    public function getOptions()
    {
        $params = request()->post('params');
        $params = explode(',', $params);
        foreach ($params as $key => $value) {
            if ($value == 'info_category') {
                $options[$value] = $this->getCats([], 'child');
            }

            if ($value == 'category_list') {
                $options[$value] = $this->getCats([], 'list');
            }

        }
        $data = $options;
        return $this->success(__('Operation successful'), $data);
    }

    /**
     * 生成分类select列表
     * @param  [type] $sel [选中项]
     * @return [type]      [数组]
     */
    private function getCats($sel, $type = 'select')
    {

        $menus = Db::name('cat')->alias('a')->join("cat_description b", 'a.cat_id=b.cat_id and b.language_id=' . $this->lang_id, 'left')->where('a.group', '文章')->column("a.cat_id as id,b.cat_name as name,a.pid as parentid,a.sorted as `order`", "a.cat_id");

        $tree = new InitTree;
        $tree->set_tree($menus);
        if ($type == 'select') {

            $cat_options = $tree->get_tree_multi(0, "<option value=\$id \$selected>\$spacer\$name</option>", $sel);
        } elseif ($type == 'child') {
            $cats = $tree->listToTree(0);
            foreach ($cats as $key => $value) {
                $cat_options[$value['id']] = $value;
            }
        } elseif ($type == 'list') {
            $cat_options = $menus;
        } else {
            $cat_options = $tree->get_childs(0);
        }

        return $cat_options;

    }

    /**
     * 分类名称
     * @param  [type] $v [description]
     * @return [type]    [description]
     */
    private function getLangCatName($v)
    {
        $cat_name = [];

        if ($v->cats) {
            $cats = $v->cats->toArray();
            foreach ((array) $cats as $v) {
                if ($v['language_id'] != $this->lang_id) {
                    continue;
                }
                $cat_name[] = $v['cat_name'];
            }
        }
        return implode(',', $cat_name);
    }

    /**
     * 任务详情
     * @return [type] [description]
     */
    public function detail()
    {
        $id   = request()->get("id");
        if(!$id){
            return $this->error('error request!');
        }
        $data = cModel::with(['description', 'infoCats.description'])->find($id);


        $prev         = cModel::with(['description', 'infoCats.description'])->where("info_id", '<', $id)->order("info_id", "desc")->find();
        $next         = cModel::with(['description', 'infoCats.description'])->where("info_id", '>', $id)->order("info_id", "asc")->find();
        $prev && $prev->route =  createUrl('art',$prev->title,$prev->info_id);;
        $next && $next->route =  createUrl('art',$next->title,$next->info_id);;
        $data['prev'] = $prev;
        $data['next'] = $next;

        $data->inc('browse_num', 1)->update();
        return $this->success(__('Operation successful'), $data);
    }

    /**
     * 文章分类数据
     * @return [type] [description]
     */
    public function listbycat()
    {
        $limit     = $this->request->get("limit/d", 10);
        $cat_limit = $this->request->get("cat_limit/d", 5);
        $cat_id    = $this->request->get("cat_id");
        $tmp       = $this->getCats([], 'list');
        $cats      = [];
        if ($cat_id) {
            $cat_id = explode(',', $cat_id);
            foreach ($tmp as $k => $v) {
                if (in_array($k, $cat_id)) {
                    $cats[$k] = $v;
                }
            }
        } else {

            $i = 0;
            foreach ($tmp as $k => $v) {
                if ($i >= $cat_limit) {
                    break;
                }
                $i++;
                $cats[$k] = $v;
            }
        }
        
        foreach ($cats as $k => $v) {
            $res = cModel::alias("a")->with("description")->join("info_cat b", "a.info_id=b.info_id")->where("b.cat_id", $v['cat_id'])->limit($limit)->select()->toArray();
            foreach ($res as $kt => $vt) {
                $vt['route'] = createUrl('art',$vt['title'],$vt['info_id']);
                $res[$kt] = $vt;
            }
            $v['_list'] =$res;
            $cats[$k]   = $v;
        }
        return $this->success(__('Operation successful'), $cats);

    }

}
